//
//  LocationManager.m
//  SportSocial
//
//  Created by yull on 15/1/1.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "LocationManager.h"
#import "UserNet.h"

@implementation LocationManager

+ (instancetype)shareInstance
{
    static LocationManager *manager = nil;
    static dispatch_once_t predicate ;
    dispatch_once(&predicate, ^{
        manager = [[LocationManager alloc] init];
    });
    return manager;
}

- (void)dealloc
{
    [[CurrentUser shareInstance] removeObserver:self forKeyPath:@"token"];
}

- (instancetype)init
{
    if (self = [super init]) {
        [BMKLocationService setLocationDesiredAccuracy:100.0f];
        self.locationService = [[BMKLocationService alloc] init];
        self.locationService.delegate = self;
        [self.locationService startUserLocationService];
    }
    return self;
}

- (void)willStartLocatingUser
{
    NSLog(@"开始定位!");
}

- (void)didStopLocatingUser
{
    NSLog(@"停止定位");
}

- (void)didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"定位失败!=%@",error.localizedDescription);
}

- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    self.location = userLocation.location;
    
    //测试数据
//    double longitude = 121.48033;
////    
//    double latitude = 31.211286;
////    
//    self.location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
    
    [self getAddressFromServer];
    [self updateUserLocation];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"UserLocationDidChange" object:self.location];
    
    [self.locationService stopUserLocationService];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10*60 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.locationService startUserLocationService];
    });
}

- (void)updateUserLocation
{
    if ([CurrentUser shareInstance].token.length) {
        [UserNet locateWithToken:[CurrentUser shareInstance].token latitude:self.location.coordinate.latitude longitude:self.location.coordinate.longitude successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
            BOOL success = [[responseObject objectForKey:@"success"] boolValue];
            if (success) {
                NSLog(@"更新位置成功");
            }
        } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"网络连接失败");
        }];
    } else {
        [[CurrentUser shareInstance] addObserver:self forKeyPath:@"token" options:NSKeyValueObservingOptionNew context:nil];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"token"]) {
        [self updateUserLocation];
    }
}

- (void)getAddressFromServer
{
    if (self.address.length == 0) {
        if (!self.search) {
            self.search = [[BMKGeoCodeSearch alloc] init];
            self.search.delegate = self;
        }
        
        BMKReverseGeoCodeOption *option = [[BMKReverseGeoCodeOption alloc] init];
        option.reverseGeoPoint = self.location.coordinate;
        
        BOOL ret = [self.search reverseGeoCode:option];
        if (ret) {
            NSLog(@"获取地理位置成功!");
        }
    }
}

- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    if (!error) {
        self.address = result.address;
    }
}

@end
